﻿package newXgame.utils
{
	import anshe.error.CreateError;
	
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.geom.Rectangle;
	import flash.utils.Timer;
	
	import newXgame.utils.struct.SpriteDragStruct;
	
	public final class SpriteTools extends Object
	{
		private static var dragArray:Array;
		private static var t:Timer;			//	用于刷新显示的计时器对象
		
		//	给一个 Sprite 类或其派生类添加拖动事件
		public static function InitDragEvent(spr:Sprite, lockCent:Boolean = false, rect:Rectangle = null):void
		{
			if(!dragArray)
			{
				dragArray = new Array();
			}
			dragArray.push(new SpriteDragStruct(spr, lockCent, rect));
			
			spr.addEventListener(MouseEvent.MOUSE_DOWN, onStartDisplay);
			spr.addEventListener(MouseEvent.MOUSE_UP, onStopDisplay);
		}
		
		//	删除 Sprite 类的拖动事件
		public static function RemoveDragEvent(spr:Sprite):void
		{
			spr.removeEventListener(MouseEvent.MOUSE_DOWN, onStartDisplay);
			spr.removeEventListener(MouseEvent.MOUSE_UP, onStopDisplay);
		}
		
		private static function FindSprite(spr:Sprite):SpriteDragStruct
		{
			if(dragArray)
			{
				for(var i:int = 0; i < dragArray.length; i++)
				{
					var obj:SpriteDragStruct = dragArray[i];
					if(obj.spr.name == spr.name)
					{
						return obj;
					}
				}
			}
			
			return null;
		}
		
		//	开始拖动
		private static function onStartDisplay(e:MouseEvent):void
		{
			var spr:Sprite = (e.target as Sprite);
			if(spr)
			{
				trace(FindSprite(spr));
				spr.startDrag();
				if(spr.stage)
				{
					spr.stage.addEventListener(MouseEvent.MOUSE_UP, onStopDisplay);
				}
				if(!t)
				{
					var t:Timer = new Timer(10);
					t.addEventListener(TimerEvent.TIMER, onRushDrag);
				}
				t.start();
			}
		}
		
		//	停止拖动
		private static function onRushDrag(e:TimerEvent):void
		{
			e.updateAfterEvent();
		}
		
		private static function onStopDisplay(e:MouseEvent):void
		{
			var spr:Sprite = (e.target as Sprite);
			if(spr)
			{
				spr.stopDrag();
				if(spr.stage)
				{
					spr.stage.removeEventListener(MouseEvent.MOUSE_UP, onStopDisplay);
				}
				if(t)
				{
					t.stop();
				}
			}
		}
		
		public function SpriteTools()
		{
			throw new CreateError("SpriteTools");
		}		
	}
}